const { ipcMain } = require('electron');
const { getCaseDatabaseInfo, ensureCaseTables } = require('../database/knex');
const ProfileEngine = require('../services/ProfileEngine');
const ProfileService = require('../services/ProfileService');

function registerProfileHandlers() {
    // ========== ProfileEngine handlers (existing) ==========

    // Build profile cache
    ipcMain.handle('profile:build', async (event, caseId) => {
        try {
            const { dbPath } = await getCaseDatabaseInfo(caseId);
            await ProfileEngine.buildProfileCache(caseId, dbPath);
            return { success: true };
        } catch (error) {
            console.error('Failed to build profile:', error);
            throw error;
        }
    });

    // Get entities list
    ipcMain.handle('profile:get-entities', async (event, caseId) => {
        try {
            const { dbPath } = await getCaseDatabaseInfo(caseId);
            return await ProfileEngine.getEntities(caseId, dbPath);
        } catch (error) {
            console.error('Failed to get entities:', error);
            throw error;
        }
    });

    // Get graph data
    ipcMain.handle('profile:get-graph', async (event, caseId) => {
        try {
            const { dbPath } = await getCaseDatabaseInfo(caseId);
            return await ProfileEngine.getGraphData(caseId, dbPath);
        } catch (error) {
            console.error('Failed to get graph data:', error);
            throw error;
        }
    });

    // Get timeline
    ipcMain.handle('profile:get-timeline', async (event, { caseId, identifier }) => {
        try {
            console.log(`[IPC] profile:get-timeline called with caseId=${caseId}, identifier=${identifier}`);
            const { dbPath } = await getCaseDatabaseInfo(caseId);
            return await ProfileEngine.getTimeline(caseId, dbPath, identifier);
        } catch (error) {
            console.error('Failed to get timeline:', error);
            throw error;
        }
    });

    // ========== ProfileService handlers (new) ==========

    /**
     * 创建或更新人物档案
     */
    ipcMain.handle('profile.create', async (event, { caseId, data }) => {
        try {
            const { knex: caseKnex } = await getCaseDatabaseInfo(caseId);
            await ensureCaseTables(caseKnex);

            const profileId = await ProfileService.createOrUpdateProfile(caseKnex, data);
            return { success: true, profileId };
        } catch (error) {
            console.error('[Profile Create Error]', error);
            return { success: false, message: error.message };
        }
    });

    /**
     * 获取档案详情
     */
    ipcMain.handle('profile.get', async (event, { caseId, profileId }) => {
        try {
            const { knex: caseKnex } = await getCaseDatabaseInfo(caseId);
            const profile = await ProfileService.getProfile(caseKnex, profileId);
            return { success: true, data: profile };
        } catch (error) {
            console.error('[Profile Get Error]', error);
            return { success: false, message: error.message };
        }
    });

    /**
     * 搜索档案
     */
    ipcMain.handle('profile.search', async (event, { caseId, query, options }) => {
        try {
            const { knex: caseKnex } = await getCaseDatabaseInfo(caseId);
            const result = await ProfileService.searchProfiles(caseKnex, query, options);
            return { success: true, ...result };
        } catch (error) {
            console.error('[Profile Search Error]', error);
            return { success: false, message: error.message, items: [], total: 0 };
        }
    });

    /**
     * 通过身份证查找档案
     */
    ipcMain.handle('profile.findByIdCard', async (event, { caseId, idCard }) => {
        try {
            const { knex: caseKnex } = await getCaseDatabaseInfo(caseId);
            const profile = await ProfileService.findByIdCard(caseKnex, idCard);
            return { success: true, data: profile };
        } catch (error) {
            console.error('[Profile FindByIdCard Error]', error);
            return { success: false, message: error.message };
        }
    });

    /**
     * 获取档案列表（分页）
     */
    ipcMain.handle('profile.list', async (event, { caseId, page = 1, pageSize = 20, entityType }) => {
        try {
            const { knex: caseKnex } = await getCaseDatabaseInfo(caseId);
            const result = await ProfileService.searchProfiles(caseKnex, '', {
                entity_type: entityType,
                page,
                pageSize
            });
            return { success: true, ...result };
        } catch (error) {
            console.error('[Profile List Error]', error);
            return { success: false, message: error.message, items: [], total: 0 };
        }
    });

    /**
     * 从银行流水提取档案
     */
    ipcMain.handle('profile.extractFromBank', async (event, { caseId, tableName }) => {
        try {
            const { knex: caseKnex } = await getCaseDatabaseInfo(caseId);
            await ensureCaseTables(caseKnex);

            const result = await ProfileService.extractFromBankTransactions(caseKnex, tableName);
            return { success: true, ...result };
        } catch (error) {
            console.error('[Profile ExtractFromBank Error]', error);
            return { success: false, message: error.message };
        }
    });
}

module.exports = { registerProfileHandlers };

